package service;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import nl.knaw.dans.common.dbflib.Field;
import nl.knaw.dans.common.dbflib.IfNonExistent;
import nl.knaw.dans.common.dbflib.Record;
import nl.knaw.dans.common.dbflib.Table;
import nl.knaw.dans.common.dbflib.Type;

/**
 * Read DBF File
 * @author Gustavo
 */
public class ReadDBF implements IRead {

	@Override
	public void read(File fileToRead, IRecordData rec) throws Exception {

		Table table = new Table(fileToRead);

		try {
			table.open(IfNonExistent.ERROR);

			List<Field> fields = table.getFields();

			Iterator<Record> iterator = table.recordIterator();
			while (iterator.hasNext()) {

				Record record = iterator.next();

				final Map<String, Object> m = new HashMap<String, Object>();
				for (Field field : fields) {

					Object value;
					if (Type.LOGICAL.equals(field.getType())) {
						value = record.getBooleanValue(field.getName());
					} else if (Type.NUMBER.equals(field.getType())) {
						value = record.getNumberValue(field.getName());
					} else if (Type.CHARACTER.equals(field.getType())) {
						value = record.getStringValue(field.getName());
					} else if (Type.DATE.equals(field.getType())) {
						value = record.getDateValue(field.getName());
					} else if (Type.FLOAT.equals(field.getType())) {
						value = record.getNumberValue(field.getName());
					} else if (Type.GENERAL.equals(field.getType())) {
						value = record.getStringValue(field.getName());
					} else if (Type.BINARY.equals(field.getType())) {
						// no implementado
						value = null;
					} else if (Type.PICTURE.equals(field.getType())) {
						// no implementado
						value = null;
					} else if (Type.MEMO.equals(field.getType())) {
						// no implementado
						value = null;
					} else {
						throw new Exception(
								"No se reconoce el tipo de dato para el campo "
										+ field.getName());
					}
					m.put(field.getName(), value);
				}
				rec.data(m);
			}
		} finally {
			table.close(); // siempre cerrar!!
		}
	}
}
